﻿#include "lifekeeper.h"
#include "ui_lifekeeper.h"
#include <QDebug>
#include "jmysql.h"

LifeKeeper::LifeKeeper(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LifeKeeper)
{
    ui->setupUi(this);

    Init();
}

LifeKeeper::~LifeKeeper()
{
    log.WriteLog(QStringLiteral("软件关闭."));
    // 普通变量
    delete PwdTimer;
    Thread->quit();
    Thread->wait();
    delete Thread;
    // 注册
    delete Reg;
    // 登录
    delete LabLogUser;
    delete LabLogPasswd;
    delete LEditLogUser;
    delete LabLogUserTip;
    delete LEditLogPasswd;
    delete LabLogPasswdTip;
    delete pBtnLogSure;
    delete CheckBoxRem;
    delete pBtnRegister;
    delete GLayLog;
    delete LogFram;
    // 控件变量
    delete SaveAction;
    delete FileMenu;
    delete LogInAction;
    delete BookAction;
    delete PasswdAction;
    delete ViewMenu;
    delete ToolMenu;
    delete MenuBar;
    delete ToolBar;
    delete LEditSearch;
    delete pBtnSearch;
    delete HLayPwdSearch;
    delete TabWigtPasswd;
    delete VLayPasswd;
    delete TabPwd;
    delete TabBank;
    delete TabPersonInfo;
    delete TabAccount;
    delete LEditBookSearch;
    delete pBtnBookSearch;
    delete HLayBookSearch;
    delete TabWigtBook;
    delete VLayBook;
    delete WigtBook;
    delete LbStatusTipInfo;
    delete StatusBar;
    delete VLayMain;
    delete ActionAdd;
    delete ActionDel;
    delete MenuPwd;
    delete ActionAddBook;
    delete ActionDelBook;
    delete MenuBook;
    delete ui;
}

void LifeKeeper::Init()
{
    log.WriteLog(QStringLiteral("软件开启."));
    // 窗口最大化
    this->setWindowState(Qt::WindowMaximized);
    // 设置窗口标题
    this->setWindowTitle(QStringLiteral("信息记录器"));
    TypeMode = PASSWDMODE;
    // 初始化控件
    InitCtrls();
    // 初始化变量
    InitVariates();
    InitLogFrame();
    // 加载数据
    LoadDatatoCtrl();
    // 初始化线程
    InitThreads();
}

void LifeKeeper::InitCtrls()
{
    //初始化菜单栏
    MenuBar = new QMenuBar(this);
    FileMenu = new QMenu(QStringLiteral("文件"));
    SaveAction = new QAction(QStringLiteral("保存"), this);
    ViewMenu = new QMenu(QStringLiteral("视图"));
    ToolMenu = new QMenu(QStringLiteral("工具"));
    LogInAction = new QAction(QStringLiteral("登录"), this);
    BookAction = new QAction(QStringLiteral("书籍记录"), this);
    PasswdAction = new QAction(QStringLiteral("信息记录"), this);
    connect(PasswdAction, SIGNAL(triggered()), this, SLOT(PasswdNoteSlot()));
    connect(BookAction, SIGNAL(triggered()), this, SLOT(BookNoteSlot()));
    connect(SaveAction, SIGNAL(triggered()), this, SLOT(SaveDataSlot()));
    SaveAction->setShortcut(QKeySequence("Ctrl+s"));
    FileMenu->addAction(SaveAction);
    MenuBar->addMenu(FileMenu);    
    ViewMenu->addAction(BookAction);
    ViewMenu->addAction(PasswdAction);
    MenuBar->addMenu(ViewMenu);
    MenuBar->addMenu(ToolMenu);
    MenuBar->show();
    // 初始化工具栏
    ToolBar = new QToolBar(this);
    VLayMain = new QVBoxLayout;
    LbStatusTipInfo = new QLabel(QStringLiteral("提示信息..."));
    StatusBar = new QStatusBar(this);
    ToolBar->addAction(LogInAction);
    ToolBar->addAction(PasswdAction);
    ToolBar->addAction(BookAction);
    ToolBar->show();
    VLayMain->addWidget(MenuBar);
    VLayMain->addWidget(ToolBar);
    InitPasswd();
    InitBook();
    StatusBar->addPermanentWidget(LbStatusTipInfo);
    VLayMain->addWidget(StatusBar);
    VLayMain->setContentsMargins(0, 0, 0, 5);
    this->setLayout(VLayMain);
    StatusBar->showMessage(QStringLiteral("提示信息..."));
    connect(LogInAction, SIGNAL(triggered()), this, SLOT(LoginSlot()));
}

void LifeKeeper::InitPasswd()
{
    QStringList TabHeader;
    TabHeader << QStringLiteral("名称") <<
                 QStringLiteral("类型") <<
                 QStringLiteral("账号名") <<
                 QStringLiteral("邮箱") <<
                 QStringLiteral("电话") <<
                 QStringLiteral("密码") <<
                 QStringLiteral("密码2") <<
                 QStringLiteral("备注") <<
                 QStringLiteral("Id");
    TabWigtPasswd = new QTableWidget(0, TabHeader.size());
    TabWigtPasswd->setHorizontalHeaderLabels(TabHeader);
    HLayPwdSearch = new QHBoxLayout;
    LEditSearch = new QLineEdit;
    pBtnSearch = new QPushButton(QStringLiteral("查询"));
    TabPwd = new QTabBar;
    TabBank = new QTabBar;
    TabPersonInfo = new QTabBar;
    TabAccount = new QTabWidget;
    VLayPasswd = new QVBoxLayout;
    MenuPwd = new QMenu;
    ActionAdd = new QAction(QStringLiteral("添加"), this);
    ActionDel = new QAction(QStringLiteral("删除"), this);
    MenuPwd->addAction(ActionAdd);
    MenuPwd->addAction(ActionDel);
    HLayPwdSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayPwdSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayPwdSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayPwdSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayPwdSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayPwdSearch->addWidget(LEditSearch);
    HLayPwdSearch->addWidget(pBtnSearch);
    VLayPasswd->addLayout(HLayPwdSearch);
    TabWigtPasswd->setColumnWidth(3, 200);
    TabWigtPasswd->horizontalHeader()->setSectionResizeMode(7, QHeaderView::Stretch);
    VLayPasswd->addWidget(TabWigtPasswd);
    TabAccount->addTab(TabPwd, QStringLiteral("密码本"));
    TabAccount->addTab(TabBank, QStringLiteral("银行账号"));
    TabAccount->addTab(TabPersonInfo, QStringLiteral("个人信息"));
    TabAccount->setTabShape(QTabWidget::Triangular);
    TabAccount->setTabPosition(QTabWidget::West);
    TabPwd->setLayout(VLayPasswd);
    VLayMain->addWidget(TabAccount);
    pBtnSearch->setAcceptDrops(true);
    connect(pBtnSearch, SIGNAL(clicked()), this, SLOT(PasswdSearchSlot()));
    connect(LEditSearch, SIGNAL(textChanged(QString)), this, SLOT(PasswdSearchChangedSlot(QString)));
    // 隐藏垂直表头
    TabWigtPasswd->verticalHeader()->hide();
    // 隐藏Id列
    TabWigtPasswd->setColumnHidden(8, true);
    TabWigtPasswd->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(TabWigtPasswd, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(PasswdcontextMenuEvent(QPoint)));
    connect(ActionAdd, SIGNAL(triggered()), this, SLOT(AddPasswdRowSlot()));
    connect(ActionDel, SIGNAL(triggered()), this, SLOT(DeletePasswdRowsSlot()));
}

void LifeKeeper::InitBook()
{
    VLayBook = new QVBoxLayout;
    WigtBook = new QWidget(this);
    QStringList TabHeader;
    TabHeader << QStringLiteral("书名") <<
                 QStringLiteral("类型") <<
                 QStringLiteral("作者") <<
                 QStringLiteral("作者国籍") <<
                 QStringLiteral("出版社") <<
                 QStringLiteral("阅读时间") <<
                 QStringLiteral("状态") <<
                 QStringLiteral("时长") <<
                 QStringLiteral("概括") <<
                 QStringLiteral("看书平台") <<
                 QStringLiteral("备注") <<
                 QStringLiteral("Id");
    TabWigtBook = new QTableWidget(0, TabHeader.size());
    MenuBook = new QMenu;
    ActionAddBook = new QAction(QStringLiteral("添加"), this);
    ActionDelBook = new QAction(QStringLiteral("删除"), this);
    LEditBookSearch = new QLineEdit;
    pBtnBookSearch = new QPushButton(QStringLiteral("查询"));
    HLayBookSearch = new QHBoxLayout;
    MenuBook->addAction(ActionAddBook);
    MenuBook->addAction(ActionDelBook);
    TabWigtBook->setHorizontalHeaderLabels(TabHeader);
    TabWigtBook->horizontalHeader()->setSectionResizeMode(8, QHeaderView::Stretch);
    HLayBookSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayBookSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayBookSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayBookSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayBookSearch->addSpacerItem(new QSpacerItem(20, 20, QSizePolicy::Expanding));
    HLayBookSearch->addWidget(LEditBookSearch);
    HLayBookSearch->addWidget(pBtnBookSearch);
    VLayBook->addLayout(HLayBookSearch);
    VLayBook->addWidget(TabWigtBook);
    WigtBook->setLayout(VLayBook);
    VLayMain->addWidget(WigtBook);
    WigtBook->hide();
    TabWigtBook->verticalHeader()->hide();
    // 隐藏Id列
    TabWigtBook->setColumnHidden(11, true);
    TabWigtBook->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(TabWigtBook, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(BookcontextMenuEvent(QPoint)));
    connect(ActionAddBook, SIGNAL(triggered()), this, SLOT(AddBookRowSlot()));
    connect(ActionDelBook, SIGNAL(triggered()), this, SLOT(DeleteBookRowsSlot()));
    connect(pBtnBookSearch, SIGNAL(clicked()), this, SLOT(BookSearchSlot()));
    connect(LEditBookSearch, SIGNAL(textChanged(QString)),
            this, SLOT(BookSearchChangeSlot(QString)));
}

void LifeKeeper::InitVariates()
{
    IsLog = false;
    UserId = -1;
    PwdIndex = 0;
    BookIndex = 0;
    PwdTimer = new QTimer(this);
    connect(PwdTimer, SIGNAL(timeout()), this, SLOT(SavePasswdInfoSlot()));
    PwdTimer->start(60 * 1000); // 30s保存一次数据
}

void LifeKeeper::InitLogFrame()
{
    LogFram = new QDialog(this);
    LogFram->setWindowTitle(QStringLiteral("登录"));
    LabLogUser = new QLabel(QStringLiteral("用户名:"));
    LabLogPasswd = new QLabel(QStringLiteral("密  码:"));
    LEditLogUser = new QLineEdit(QStringLiteral(""));
    LabLogUserTip = new QLabel(QStringLiteral(""));
    LEditLogPasswd = new QLineEdit(QStringLiteral(""));
    LabLogPasswdTip = new QLabel(QStringLiteral(""));
    pBtnLogSure = new QPushButton(QStringLiteral("登录"), LogFram);
    pBtnLogFail = new QPushButton(QStringLiteral("取消"), LogFram);
    CheckBoxRem = new QCheckBox(QStringLiteral("记住密码"));
    pBtnRegister = new QPushButton(QStringLiteral("注册"));
    GLayLog = new QGridLayout;
    LEditLogPasswd->setEchoMode(QLineEdit::Password);
    pBtnRegister->setFlat(true);
    GLayLog->addWidget(LabLogUser, 0, 0, 1, 1);
    GLayLog->addWidget(LEditLogUser, 0, 1, 1, 1);
    GLayLog->addWidget(LabLogUserTip, 0, 2, 1, 1);
    GLayLog->addWidget(LabLogPasswd, 1, 0, 1, 1);
    GLayLog->addWidget(LEditLogPasswd, 1, 1, 1, 1);
    GLayLog->addWidget(LabLogPasswdTip, 1, 2, 1, 1);
    GLayLog->addWidget(CheckBoxRem, 2, 0, 1, 1);
    GLayLog->addWidget(pBtnRegister, 2, 1, 1, 1);
    GLayLog->addWidget(pBtnLogSure, 3, 0, 1, 1);
    GLayLog->addWidget(pBtnLogFail, 3, 1, 1, 1);
    GLayLog->setColumnStretch(0, 1);
    GLayLog->setColumnStretch(1, 2);
    GLayLog->setHorizontalSpacing(10);
    GLayLog->setVerticalSpacing(5);
    GLayLog->setContentsMargins(50, 50, 50, 50);
    LogFram->setLayout(GLayLog);
    pBtnLogSure->setGeometry(LogFram->width() / 5 * 4, LogFram->height() / 5 * 4, 40, 20);
    pBtnLogSure->setAutoDefault(true);
    LogFram->setGeometry(this->width() / 2, this->height() / 2, 400, 300);
    connect(pBtnLogSure, SIGNAL(clicked()), this, SLOT(LogSuccessSlot()));
    connect(pBtnLogFail, SIGNAL(clicked()), this, SLOT(LogFailedSlot()));
    connect(pBtnRegister, SIGNAL(clicked()), this, SLOT(RegisterUser()));
    connect(LogFram, SIGNAL(finished(int)), this, SLOT(closeLog()));
    connect(CheckBoxRem, SIGNAL(clicked()), this, SLOT(RemeberPasswdSlot()));
    LogFram->show();
    // 注册
    Reg = new RegisterForm;
    connect(Reg, SIGNAL(closeWind()), this, SLOT(closeRefister()));
    connect(Reg, SIGNAL(RegisterSuccess(UserInformation)), this, SLOT(RefisterSuccess(UserInformation)));
    // 加载
    QSettings cfg("Config.cfg", QSettings::IniFormat);
    LEditLogUser->setText(cfg.value("/LogInfo/User").toString());
    if(cfg.value("/LogInfo/RemeberPwd").toInt() == 1) {
        QByteArray ba = cfg.value("/LogInfo/Passwd").toByteArray();
        LEditLogPasswd->setText(ba.fromBase64(ba));
        CheckBoxRem->setChecked(true);
    }
}

void LifeKeeper::InitThreads()
{
    SyncThread = new DataSyncThread;
    Thread = new QThread;
    SyncThread->moveToThread(Thread);
    connect(Thread, SIGNAL(finished()), SyncThread, SLOT(deleteLater()));
    connect(this, SIGNAL(StartSyncData(int)), SyncThread, SLOT(SyncData(int)));
    Thread->start();
}

/*************************************
* @projectName   LifeKeeper
* @brief         获取当前时间
* @mesc          返回时间是否带毫秒
* @return        返回日期时间字符串
* @author        LJJ
* @date          2018-12-26
*************************************/
QString LifeKeeper::GetCurrentTime(bool msec)
{
    if(msec)
        return QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    else
        return QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
}

void LifeKeeper::LoadDatatoCtrl()
{
    PwdDataList.clear();
    BookDataList.clear();
    DJson.ReadData(PwdDataList, BookDataList);
    for(auto i = TabWigtBook->rowCount(); i > 0; i--)
        TabWigtBook->removeRow(i);
    for(auto i = TabWigtPasswd->rowCount(); i > 0; i--)
        TabWigtPasswd->removeRow(i);
    for(auto i = 0; i < PwdDataList.size(); i++)
        SetPasswdData(PwdDataList.at(i));
    for(auto i = 0; i < BookDataList.size(); i++)
        SetBookData(BookDataList.at(i));
}

void LifeKeeper::SetPasswdData(JDPasswdNote Data)
{
    int Cnt = TabWigtPasswd->rowCount();
    TabWigtPasswd->insertRow(Cnt);
    TabWigtPasswd->setItem(Cnt, 0, new QTableWidgetItem(Data.Name));
    TabWigtPasswd->setItem(Cnt, 1, new QTableWidgetItem(Data.Type));
    TabWigtPasswd->setItem(Cnt, 2, new QTableWidgetItem(Data.Account));
    TabWigtPasswd->setItem(Cnt, 3, new QTableWidgetItem(Data.Email));
    TabWigtPasswd->setItem(Cnt, 4, new QTableWidgetItem(Data.Phone));
    TabWigtPasswd->setItem(Cnt, 5, new QTableWidgetItem(Data.Pwd));
    TabWigtPasswd->setItem(Cnt, 6, new QTableWidgetItem(Data.Pwd2));
    TabWigtPasswd->setItem(Cnt, 7, new QTableWidgetItem(Data.Remark));
    TabWigtPasswd->setItem(Cnt, 8, new QTableWidgetItem(QString::number(Data.Index)));
    if(Data.Index > PwdIndex)
        PwdIndex = Data.Index;
}

void LifeKeeper::SetBookData(JDBookData Data)
{
    int Cnt = TabWigtBook->rowCount();
    TabWigtBook->insertRow(Cnt);
    TabWigtBook->setItem(Cnt, 0, new QTableWidgetItem(Data.BookName));
    TabWigtBook->setItem(Cnt, 1, new QTableWidgetItem(Data.BookType));
    TabWigtBook->setItem(Cnt, 2, new QTableWidgetItem(Data.BookAuthor));
    TabWigtBook->setItem(Cnt, 3, new QTableWidgetItem(Data.AuthorHome));
    TabWigtBook->setItem(Cnt, 4, new QTableWidgetItem(Data.BookPunlish));
    TabWigtBook->setItem(Cnt, 5, new QTableWidgetItem(Data.DataTime));
    TabWigtBook->setItem(Cnt, 6, new QTableWidgetItem(Data.BookStatus));
    TabWigtBook->setItem(Cnt, 7, new QTableWidgetItem(Data.TimeLen));
    TabWigtBook->setItem(Cnt, 8, new QTableWidgetItem(Data.BookSummary));
    TabWigtBook->setItem(Cnt, 9, new QTableWidgetItem(Data.BookPlat));
    TabWigtBook->setItem(Cnt, 10, new QTableWidgetItem(Data.Remark));
    TabWigtBook->setItem(Cnt, 11, new QTableWidgetItem(QString::number(Data.Index)));
    if(Data.Index > BookIndex)
        BookIndex = Data.Index;
}

void LifeKeeper::GetAndSavePasswdData()
{
    qDebug()<< QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") <<
               " : save passwd info...";
    for(int i = 0; i < TabWigtPasswd->rowCount(); i++) {
        JDPasswdNote pwd;
        pwd.UserId = UserId;
        bool Invaild = false;
        for(int j = 0; j < TabWigtPasswd->columnCount(); j++) {
            if(TabWigtPasswd->item(i, j) != 0) {
                Invaild = true;
                break;
            }
        }
        if(Invaild) {
            if(TabWigtPasswd->item(i, 0) == 0)
                pwd.Name = "";
            else
                pwd.Name = TabWigtPasswd->item(i, 0)->text();
            if(TabWigtPasswd->item(i, 1) == 0)
                pwd.Type = "";
            else
                pwd.Type = TabWigtPasswd->item(i, 1)->text();
            if(TabWigtPasswd->item(i, 2) == 0)
                pwd.Account = "";
            else
                pwd.Account = TabWigtPasswd->item(i, 2)->text();
            if(TabWigtPasswd->item(i, 3) == 0)
                pwd.Email = "";
            else
                pwd.Email = TabWigtPasswd->item(i, 3)->text();
            if(TabWigtPasswd->item(i, 4) == 0)
                pwd.Phone = "";
            else
                pwd.Phone = TabWigtPasswd->item(i, 4)->text();
            if(TabWigtPasswd->item(i, 5) == 0)
                pwd.Pwd = "";
            else
                pwd.Pwd = TabWigtPasswd->item(i, 5)->text();
            if(TabWigtPasswd->item(i, 6) == 0)
                pwd.Pwd2 = "";
            else
                pwd.Pwd2 = TabWigtPasswd->item(i, 6)->text();
            if(TabWigtPasswd->item(i, 7) == 0)
                pwd.Remark = "";
            else
                pwd.Remark = TabWigtPasswd->item(i, 7)->text();
            if(TabWigtPasswd->item(i, 8) == 0) {
                ++PwdIndex;
                pwd.Index = PwdIndex;
                TabWigtPasswd->setItem(i, 8, new QTableWidgetItem(QString::number(PwdIndex)));
                PwdDataList.push_back(pwd);
            }
            else {
                pwd.Index = TabWigtPasswd->item(i, 8)->text().toInt();
            }
            DJson.AddPasswdData(i, pwd);
        }
    }
    StatusBar->showMessage(GetCurrentTime(false) + QStringLiteral(": 保存完密码信息"));
}

bool LifeKeeper::IsMatched(QString Src, QString Dest)
{
    if(Dest.isEmpty() || Src.isEmpty())
        return false;
    QRegExp Rx(Dest);
    int t = Rx.indexIn(Src);
    if(t < 0)
        return false;
    else
        return true;
}

void LifeKeeper::SearchPasswd()
{
    QString Search = LEditSearch->text();
    for(int i = 0; i < TabWigtPasswd->rowCount(); i++) {
        bool IsExist = false;
        for(int j = 0; j < TabWigtPasswd->columnCount(); j++) {
            if(TabWigtPasswd->item(i, j) != 0) {
                QString CellText = TabWigtPasswd->item(i, j)->text();
                if(IsMatched(CellText, Search)) {
                    TabWigtPasswd->setRowHidden(i, false);
                    IsExist = true;
                    break;
                }
            }
        }
        if(!IsExist)
            TabWigtPasswd->setRowHidden(i, true);
    }
}

void LifeKeeper::DisplayPasswd(bool show)
{
    for(int i = 0; i < TabWigtPasswd->rowCount(); i++) {
        TabWigtPasswd->setRowHidden(i, !show);
    }
}

void LifeKeeper::GetAndSaveBookData()
{
    qDebug()<< QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") <<
               " : save Book info...";
//    DataList.DeleteTypeData("JDataFile.jdf", "Books");
    for(int i = 0; i < TabWigtBook->rowCount(); i++) {
        JDBookData Book;
        Book.UserId = UserId;
        bool Invaild = false;
        for(int j = 0; j < TabWigtBook->columnCount(); j++) {
            if(TabWigtBook->item(i, j) != 0) {
                Invaild = true;
                break;
            }
        }
        if(Invaild) {
            if(TabWigtBook->item(i, 0) == 0)
                Book.BookName = "";
            else
                Book.BookName = TabWigtBook->item(i, 0)->text();
            if(TabWigtBook->item(i, 1) == 0)
                Book.BookType = "";
            else
                Book.BookType = TabWigtBook->item(i, 1)->text();
            if(TabWigtBook->item(i, 2) == 0)
                Book.BookAuthor = "";
            else
                Book.BookAuthor = TabWigtBook->item(i, 2)->text();
            if(TabWigtBook->item(i, 3) == 0)
                Book.AuthorHome = "";
            else
                Book.AuthorHome = TabWigtBook->item(i, 3)->text();
            if(TabWigtBook->item(i, 4) == 0)
                Book.BookPunlish = "";
            else
                Book.BookPunlish = TabWigtBook->item(i, 4)->text();
            if(TabWigtBook->item(i, 5) == 0)
                Book.DataTime = "";
            else
                Book.DataTime = TabWigtBook->item(i, 5)->text();
            if(TabWigtBook->item(i, 6) == 0)
                Book.BookStatus = "";
            else
                Book.BookStatus = TabWigtBook->item(i, 6)->text();
            if(TabWigtBook->item(i, 7) == 0)
                Book.TimeLen = "";
            else
                Book.TimeLen = TabWigtBook->item(i, 7)->text();
            if(TabWigtBook->item(i, 8) == 0)
                Book.BookSummary = "";
            else
                Book.BookSummary = TabWigtBook->item(i, 8)->text();
            if(TabWigtBook->item(i, 9) == 0)
                Book.BookPlat = "";
            else
                Book.BookPlat = TabWigtBook->item(i, 9)->text();
            if(TabWigtBook->item(i, 10) == 0)
                Book.Remark = "";
            else
                Book.Remark = TabWigtBook->item(i, 10)->text();

            if(TabWigtBook->item(i, 11) == 0) {
                ++BookIndex;
                Book.Index = BookIndex;
                TabWigtBook->setItem(i, 11, new QTableWidgetItem(QString::number(BookIndex)));
                BookDataList.push_back(Book);
            }
            else {
                Book.Index = TabWigtBook->item(i, 11)->text().toInt();
            }
            DJson.AddBookData(i, Book);
        }
    }
    StatusBar->showMessage(GetCurrentTime(false) + QStringLiteral(": 保存完书籍信息"));
}

void LifeKeeper::DisplayBook(bool show)
{
    for(int i = 0; i < TabWigtBook->rowCount(); i++) {
        TabWigtBook->setRowHidden(i, !show);
    }
}

void LifeKeeper::SearchBook()
{
    QString Search = LEditBookSearch->text();
    for(int i = 0; i < TabWigtBook->rowCount(); i++) {
        bool IsExist = false;
        for(int j = 0; j < TabWigtBook->columnCount(); j++) {
            if(TabWigtBook->item(i, j) != 0) {
                QString CellText = TabWigtBook->item(i, j)->text();
                if(IsMatched(CellText, Search)) {
                    TabWigtBook->setRowHidden(i, false);
                    IsExist = true;
                    break;
                }
            }
        }
        if(!IsExist)
            TabWigtBook->setRowHidden(i, true);
    }
}

void LifeKeeper::Sleep(unsigned int Sec)
{
    QTime time;
    time.start();
    while(time.elapsed() < Sec)
        QCoreApplication::processEvents();
}

// ----------------事件函数----------------------

void LifeKeeper::resizeEvent(QResizeEvent *e)
{
    qDebug() << e;    
}

void LifeKeeper::PasswdNoteSlot()
{
    TabAccount->show();
    WigtBook->hide();
}

void LifeKeeper::BookNoteSlot()
{
    WigtBook->show();
    TabAccount->hide();
}

void LifeKeeper::PasswdcontextMenuEvent(const QPoint &Pos)
{
    MenuPwd->move(cursor().pos());
    MenuPwd->show();
    qDebug() << Pos;
}

void LifeKeeper::BookcontextMenuEvent(const QPoint &Pos)
{
    MenuBook->move(cursor().pos());
    MenuBook->show();
    qDebug() << "Book: " << Pos;
}

void LifeKeeper::AddPasswdRowSlot()
{
    TabWigtPasswd->setRowCount(TabWigtPasswd->rowCount() + 1);
}

void LifeKeeper::DeletePasswdRowsSlot()
{
    QList<QTableWidgetSelectionRange> List = TabWigtPasswd->selectedRanges();
    if(List.size() > 0) {
        for(int i = List.at(0).bottomRow(); i >= List.at(0).topRow(); i--) {
            TabWigtPasswd->removeRow(i);
        }
    }
    GetAndSavePasswdData();
}

void LifeKeeper::AddBookRowSlot()
{
    TabWigtBook->setRowCount(TabWigtBook->rowCount() + 1);
}

void LifeKeeper::DeleteBookRowsSlot()
{
    QList<QTableWidgetSelectionRange> List = TabWigtBook->selectedRanges();
    if(List.size() > 0) {
        for(int i = List.at(0).bottomRow(); i >= List.at(0).topRow(); i--) {
            TabWigtBook->removeRow(i);
        }
    }
//    GetAndSavePasswdData();
}

void LifeKeeper::LoginSlot()
{
    if(IsLog) {
#if 0
        for(auto i = TabWigtPasswd->rowCount(); i >= 0; i--)
            TabWigtPasswd->removeRow(i);
        for(auto i = TabWigtBook->rowCount(); i >= 0; i--)
            TabWigtBook->removeRow(i);
#endif
        LogInAction->setText(QStringLiteral("登录"));
        IsLog = false;
        UserId = -1;
    }
    else {
        pBtnLogSure->setEnabled(true);
        LogFram->show();
    }
}

void LifeKeeper::SaveDataSlot()
{
    GetAndSavePasswdData();
    GetAndSaveBookData();
    DJson.SaveData();
    if(IsLog)
        emit StartSyncData(UserId);
    if(PwdTimer->isActive()) {
        PwdTimer->stop();
        PwdTimer->start(60000);
    }
}

void LifeKeeper::SavePasswdInfoSlot()
{
    GetAndSavePasswdData();
    GetAndSaveBookData();
    // 线程同步数据库数据
    if(IsLog)
        emit StartSyncData(UserId);
}

void LifeKeeper::PasswdSearchSlot()
{
    QString SearchText = LEditSearch->text();
    if(SearchText.isEmpty()) {
        DisplayPasswd(true);
        return;
    }
    SearchPasswd();
}

void LifeKeeper::PasswdSearchChangedSlot(QString Text)
{
    if(Text.isEmpty()) {
        DisplayPasswd(true);
        return;
    }
    SearchPasswd();
}

void LifeKeeper::BookSearchSlot()
{
    QString SearchText = LEditBookSearch->text();
    if(SearchText.isEmpty()) {
        DisplayBook(true);
        return;
    }
    SearchBook();
}

void LifeKeeper::BookSearchChangeSlot(QString Text)
{
    if(Text.isEmpty()) {
        DisplayBook(true);
        return;
    }
    SearchBook();
}

void LifeKeeper::LogSuccessSlot()
{
    pBtnLogSure->setEnabled(false);
    QSettings cfg("Config.cfg", QSettings::IniFormat);
    cfg.setValue("/LogInfo/User", LEditLogUser->text());
    cfg.setValue("/LogInfo/Passwd", LEditLogPasswd->text().toUtf8().toBase64());
    JMySQL jsql;
    UserInformation UserInfo;
    QString UserName = LEditLogUser->text();
    if(jsql.QueryLogInfo(UserName, UserInfo)) {
        qDebug() << "User:" << UserInfo.User << ", Passwd:" << UserInfo.Passwd;
        if(!UserInfo.User.isEmpty()) {
            QString Pwd = LEditLogPasswd->text();
            if(!UserInfo.Passwd.isEmpty() && UserInfo.Passwd == Pwd) {
                LabLogUserTip->setText(QStringLiteral("登录成功！"));
                Sleep(1000);
                LabLogUserTip->setText(QStringLiteral(""));
                qDebug() << "登录成功！";
                UserId = UserInfo.Id;
                IsLog = true;
                LogInAction->setText(QStringLiteral("退出"));
//                LoadDatatoCtrl();
                LogFram->close();
            }
            else {
                LabLogPasswdTip->setText(QStringLiteral("密码错误！"));
                Sleep(1000);
                LabLogPasswdTip->setText(QStringLiteral(""));
                pBtnLogSure->setEnabled(true);
                qDebug() << "密码错误！";
                log.WriteLog("登录失败，密码错误！");
            }
        }
        else {
            LabLogUserTip->setText(QStringLiteral("用户不存在，请先注册！"));
            Sleep(1000);
            LabLogUserTip->setText(QStringLiteral(""));
            pBtnLogSure->setEnabled(true);
            qDebug() << "用户不存在！";
            log.WriteLog("登录失败，用户不存在！");
        }
    }
    else {
        pBtnLogSure->setEnabled(true);
        LabLogUserTip->setText(QStringLiteral("登录失败，无法连接数据库！"));
        Sleep(1000);
        LabLogUserTip->setText(QStringLiteral(""));
        log.WriteLog("登录失败，无法连接数据库！");
    }
}

void LifeKeeper::LogFailedSlot()
{
    qDebug() << "cancel log...";
    LogFram->close();
}

void LifeKeeper::FinishSyncData()
{
    qDebug() << "完成数据同步...";
}

void LifeKeeper::RegisterUser()
{
    Reg->show();
    LogFram->hide();
}

void LifeKeeper::closeRefister()
{
    Reg->hide();
    LogFram->show();
}

void LifeKeeper::RemeberPasswdSlot()
{
    if(CheckBoxRem->isChecked()) {
        QSettings cfg("Config.cfg", QSettings::IniFormat);
        cfg.setValue("/LogInfo/RemeberPwd", 1);
    }
    else {
        QSettings cfg("Config.cfg", QSettings::IniFormat);
        cfg.setValue("/LogInfo/RemeberPwd", 0);
    }
}

void LifeKeeper::RefisterSuccess(const UserInformation User)
{
    qDebug() << "注册成功，接收到注册用户信息";
    qDebug() << User.User << ", " << User.Passwd;
    LEditLogUser->setText(User.User);
    LEditLogPasswd->setText(User.Passwd);
}
